package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.client.CmnFeignClient;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.ResultCode;
import com.atguigu.yygh.enums.DictEnum;
import com.atguigu.yygh.hosp.repository.HospitalRepository;
import com.atguigu.yygh.hosp.result.Result;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.vo.hosp.DepartmentVo;
import com.atguigu.yygh.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class HospitalServiceImpl implements HospitalService {

    @Autowired
    HospitalRepository hospitalRepository;

    @Autowired
    CmnFeignClient cmnFeignClient;

    @Override
    public void saveHospital(HttpServletRequest request) {
        HashMap<String, Object> hashMap = getStringObjectHashMap(request);
        String jsonString = JSONObject.toJSONString(hashMap);
        Hospital hospital = JSONObject.parseObject(jsonString, Hospital.class);
        hospital.setLogoData(hospital.getLogoData().replace(" ","+"));
        String hoscode = hospital.getHoscode();
        Hospital extHospital = hospitalRepository.findHospitalByHoscode(hoscode);
        if (extHospital==null) {
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setStatus(1);
            hospitalRepository.save(hospital);
        } else {
            hospital.setId(extHospital.getId());
            hospital.setUpdateTime(new Date());
            hospital.setCreateTime(extHospital.getCreateTime());
            hospital.setStatus(1);
            hospitalRepository.save(hospital);
        }
    }

    /**
     *
     * @param request:HttpServletRequest request
     * @return :Result.ok()
     */
    @Override
    public Result getHospital(HttpServletRequest request) {

        HashMap<String, Object> hashMap = getStringObjectHashMap(request);
        String hoscode = hashMap.get("hoscode").toString();
        if (hoscode.isEmpty()){
            throw new YyghException(20001,"hoscode未传入经检查");
        }
        Hospital hospitalByHoscode = hospitalRepository.findHospitalByHoscode(hoscode);
        return Result.ok(hospitalByHoscode);
    }

    @Override
    public ResultCode.R findAll(int limit, int page, HospitalQueryVo hospitalQueryVo) {

        if (hospitalQueryVo==null){
            Sort sort = Sort.by(Sort.Direction.DESC,"createTime");
            Pageable pageable = PageRequest.of(page-1,limit,sort);
            Page<Hospital> hospitalPage = hospitalRepository.findAll(pageable);
            List<Hospital> content = hospitalPage.getContent();
            content.forEach(this::getHospitalParam);
            return ResultCode.R.ok().data("pages",hospitalPage);
        }

        Hospital hospitalBy = new Hospital();

        BeanUtils.copyProperties(hospitalQueryVo,hospitalBy);
        ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreCase(true).withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);
        BeanUtils.copyProperties(hospitalQueryVo,hospitalBy);
        Example< Hospital> ex = Example.of(hospitalBy,matcher);

        Sort sort = Sort.by(Sort.Direction.DESC,"createTime");
        Pageable pageable = PageRequest.of(page-1,limit,sort);

        Page<Hospital> hospitalPage = hospitalRepository.findAll(ex, pageable);
        List<Hospital> content = hospitalPage.getContent();
        content.forEach(this::getHospitalParam);
        return ResultCode.R.ok().data("pages",hospitalPage);
    }

    @Override
    public List<Dict> getDictByDictCode(String province) {

        List<Dict> dicts = cmnFeignClient.getDictByDictCode(province);

        return dicts;
    }

    @Override
    public List<Dict> findChildData(String id) {
        List<Dict> childDataById = cmnFeignClient.getChildDataById(id);
        return childDataById;
    }

    @Override
    public void updateStatus(String id, String status) {
        Hospital hospital = hospitalRepository.findById(id).get();
        hospital.setStatus(Integer.valueOf(status));
        hospitalRepository.save(hospital);
    }

    /**
     * 通过ID 查询Hospital
     * @param id
     * @return
     */
    @Override
    public Hospital getHospById(String id) {
        Hospital hospital = new Hospital();
        hospital.setId(id);
        Example<Hospital> ex = Example.of(hospital);
        Hospital hospById = hospitalRepository.findOne(ex).get();

        this.getHospitalParam(hospById);
        return hospById;
    }




    private void getHospitalParam(Hospital hospital) {
        //--->远程调用Dict进行查询
        String hostypeString = cmnFeignClient.getNameByValueAndDictCode(hospital.getHostype(), DictEnum.HOSTYPE.getDictCode());
        String cityCodeString = cmnFeignClient.getNameByValue(hospital.getCityCode());
        String districtCodeString = cmnFeignClient.getNameByValue(hospital.getDistrictCode());
        String provinceCodeString = cmnFeignClient.getNameByValue(hospital.getProvinceCode());
        hospital.getParam().put("hostypeString",hostypeString);
        hospital.getParam().put("fullAddress",provinceCodeString+cityCodeString+districtCodeString+ hospital.getAddress());
    }

    /**
     * @param request：HttpServletRequest request
     * @return ：HashMap<String, Object>
     */
    private static HashMap<String, Object> getStringObjectHashMap(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        HashMap<String, Object> hashMap = new HashMap<>();
        Set<String> keys = parameterMap.keySet();

        keys.forEach(key->{
            hashMap.put(key,parameterMap.get(key)[0]);
        });
        return hashMap;
    }


}
